package com.shuyun.demo.delay;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: shuai.chen@shuyun.com
 * @date: 2022/10/10 3:15 PM
 */
@Component
public class Demo02Producer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public SendResult sendDelayMessage(String body) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        DefaultMQProducer producer = rocketMQTemplate.getProducer();
        Message msg = new Message(Demo02Message.TOPIC, body.getBytes());
        // messageDelayLevel=1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        msg.setDelayTimeLevel(3); // 2代表5秒

        return producer.send(msg);
    }

    public SendResult sendDelayMessage2(Integer id, int delayLevel) {
        // 创建 Demo03Message 消息
        org.springframework.messaging.Message<Demo02Message> message =
                MessageBuilder.withPayload(new Demo02Message().setId(id)).build();
        // 同步发送消息
        return rocketMQTemplate.syncSend(Demo02Message.TOPIC_2, message, 30 * 1000, delayLevel);
    }

}
